<?php
// +----------------------------------------------------------------------
// | Author: Stupboy King
// +----------------------------------------------------------------------
namespace app\api\model;
use think\Config;
use think\Db;
class Driver extends Common
{
    public function order(){
        return $this->hasMany('Order','driver_id','driver_id');
    }
    
    public function user(){
        return $this->hasOne('User','user_id','user_id');
    }
    
    public function drivercard(){
        return $this->hasOne('DriverCard','driver_id','driver_id');
    }

    public function car(){
        return $this->hasOne('Car', 'car_id', 'car_id');
    }
    
    public function driveraccount(){
        return $this->hasOne('DriverAccount','driver_id','driver_id');
    }

    public function carrental(){
        return $this->hasOne('CarRental','car_rental_id','car_rental_id');
    }

    public function company(){
        return $this->hasOne('Company','company_id','company_id');
    }

    /**
     * 一对一关联提现表
     * @return type
     */
    public function Withdrawalsrecord(){
        return $this->hasOne('WithdrawalsRecord','driver_id','driver_id');
    }
    
    /**
     * 听单状态切换
    */
    public function changeStatus($driver_id=0,$status=3){
        //TODO 更新缓存司机状态
        return $this->save(['work_state' => $status],['driver_id' => $driver_id]);
    }

    /**
     * 设置定位
     * @param int $driver_id
     * @param int $lon
     * @param int $lat
     * @return false|int
     */
    public function setLocation($driver_id=0,$lon=0,$lat=0){
        return $this->save(['lon'=>$lon,'lat'=>$lat,'update_time'=>date('Y-m-d H:i:s')],['driver_id'=>$driver_id]);
    }

    /**
     * 检查公用车辆司机师傅上班
     * @param $driver_id
     * @param $car_id
     * @return array
     */
    public function checkCarWork($driver_id,$car_id){
        $where['car_id']     = $car_id;
        $where['work_state'] = ['<',4];
        $where['driver_id']  = ['<>',$driver_id];
        $otherDriver         = $this->where($where)->field('name,phone')->find();
        if(!empty($otherDriver)){
            return [0,'您绑定的车辆正在被其他司机使用:'.$otherDriver['name'].$otherDriver['phone']];
        }else{
            return [1,'ok'];
        }
    }
    /**
     * 首页数据
     * @param $driver_id
     * @return mixed
     */
    public function homeData($driver_id){
        $driver              = $this->get($driver_id);
        $data['xing']        = $driver->getAttr('star') ? : 5;
        $data['server']      = $driver->getAttr('score') ? : 100;
        $data['car_brand']   = $driver->car->carbrand ? $driver->car->carbrand->getAttr('name') : '';
        $data['car_no']      = $driver->car ? $driver->car->getAttr('number') : '';
        $data['car_model']   = $driver->car->cartype ? $driver->car->cartype->getAttr('car_type_name') : '';
        $data['rental_name'] = $driver->carrental ? $driver->carrental->getAttr('name') : '';
        $data['company_name'] = $driver->company ? $driver->company->getAttr('company_name') : '';
        $data['driver_name'] = $driver->getAttr('name');
        $data['phone']       = $driver->getAttr('phone');
        $data['sex']         = $driver->getAttr('sex');
        $data['state']       = $driver->getAttr('state') ? : 1;
        $url                 = Config::get('base.web_url');
        $data['head_img']    = $url.$driver->getAttr('head_img');
        $data['withdraw_password'] = $driver->driveraccount ? $driver->driveraccount->getAttr('withdraw_password') : '';
        $start_time          = date('Y-m-d')." 00:00:00";
        $end_time            = date('Y-m-d')." 23:59:59";
        $result = Db::view('order',[])
        ->view('order_fee',[],'order.order_id=order_fee.order_id','left')
            ->view('order_gps',[],'order.order_id = order_gps.order_id','left')
        ->where('driver_id',$driver_id)
            ->where("plan_time between  '$start_time' and '$end_time' ")
        ->field('sum(driver_money) money,count(driver_id) orders')->find();
        $data['money']       = $result['money'] ? $result['money'] : 0;
        $data['orders']      = $result['orders'];
        $data['online_time'] = 2000;
        $data['receive_rate']= $driver->getAttr('rate') ? : 100;
        return $data;
    }

    /**
     * 修改密码
     * @param $driver_id
     * @param $old
     * @param $new
     * @return mixed
     */
    public static function changePassword($driver_id,$old,$new){
        $driver = self::get($driver_id);
        $salt   = $driver->user->getAttr('salt');
        $user_id   = $driver->user->getAttr('user_id');
        return $driver->user->save(['password'=>CorePwd($new, $salt)],['password'=>CorePwd($old, $salt), 'user_id' => $user_id ]);
    }

    /**
     * 增加司机订单数量
     * @param int $driver_id
     * @param int $num
     * @return void
     */
    public function addOrderCount($driver_id,$num=1){
        $data['order_count'] = ['exp',"order_count + $num"];
        $this->save($data,['driver_id'=>$driver_id]);
    }

    /**
     * 订单费用计算
     * @param $driver_id
     * @param $oid
     * @param int $time
     * @param int $meter
     * @param int $low
     * @param int $night
     * @return mixed
     */
    public static function countFee($driver_id=0,$oid=0,$time=0,$meter=0,$low=0,$night=0){
        // TODO:司机结算车型
        $order           = Db::name('order')->find($oid);
        // 申请用车车型
        $carType         = Db::name('car_type')->find($order['car_type_id']);
        // 派车车型
        $dipatchCarType  = Db::name('car_type')->find($order['dispatch_car_type_id']);
        // 等待时间计算
        $waitTime        = Db::name('order_fee')->where('order_id',$oid)->value('wait_time');
        $wait            = round($waitTime/60) - 10 ;
        $wait            = $wait < 0 ? 0 : $wait;
        if($carType['chartered_charge']>0){
            return self::getCharterFee($carType,$time,$meter,$low,$night);
        }else{
            return self::getDailyFee($carType,$time,$meter,$low,$night,$wait,$order['is_return']);
        }
    }

    /**
     * 获取包车费用
     * @param $carType
     * @param $time
     * @param $meter
     * @param $low
     * @param $night
     * @return mixed
     */
    public static function getCharterFee($carType,$time,$meter,$low,$night){
        $starting_price  = $carType['chartered_charge']   ? : 0;
        $Pstarting_price = $carType['p_chartered_charge'] ? : 0;
        $starting_km     = $carType['chartered_km'] ? : 0;
        $starting_time   = $carType['chartered_hour'] ? : 0;
        $timeCost        = $carType['chartered_overtime'] ? : 0;
        $PTimeCost       = $carType['p_chartered_overtime'] ? : 0;
        $mileage_cost    = $carType['chartered_overrun'] ? : 0;
        $Pmileage_cost   = $carType['p_chartered_overrun'] ? : 0;
        $nightCost       = $carType['chartered_night'] ? : 0;
        $PNightCost      = $carType['p_chartered_night'] ? : 0;
        $mileFee         = $meter/1000 - $starting_km > 0 ? round(($meter/1000-$starting_km)*$mileage_cost,1) : 0;
        $PmileFee        = $meter/1000 - $starting_km > 0 ? round(($meter/1000-$starting_km)*$Pmileage_cost,1) : 0;
        $timeFee         = $time/3600 < $starting_time ? 0 : round(($time/60-$starting_time*60)*$timeCost,1);
        $PTimeFee        = $time/3600 < $starting_time ? 0 : round(($time/60-$starting_time*60)*$PTimeCost,1);
        $remoteMile      = 0;
        $remoteFee       = 0;
        $PRemoteFee      = 0;
        $lowFee          = 0;
        $PLowFee         = 0;
        $nightFee        = round($nightCost * $night/1000,1);
        $PNightFee       = round($PNightCost * $night/1000,1);
        $fee             = $starting_price + $mileFee + $remoteFee + $lowFee + $nightFee + $timeFee;
        $p_fee           = $Pstarting_price + $PmileFee + $PRemoteFee + $PLowFee + $PNightFee + $PTimeFee;
        $data['start_fee']       = $Pstarting_price;
        $data['start_fee2']      = $starting_price;
        $data['base_time']       = $starting_time;
        $data['remote_meter']    = $remoteMile;
        $data['remote_fee']      = $PRemoteFee;
        $data['remote_fee2']     = $remoteFee;
        $data['base_meter']      = $starting_km;
        $data['use_time']        = $time;
        $data['time_fee']        = $PTimeFee;
        $data['time_fee2']       = $timeFee;
        $data['low_speed_time']  = $low/60;//单位秒
        $data['low_fee']         = $PLowFee;
        $data['low_fee2']        = $lowFee;
        $data['night_meter']     = $night;
        $data['night_fee']       = $PNightFee;
        $data['night_fee2']      = $nightFee;
        $data['meter']           = $meter;
        $data['travel_fee2']     = $mileFee;
        $data['travel_fee']      = $PmileFee;
        $data['passenger_money'] = $p_fee;
        $data['driver_money']    = $fee;
        $data['company_money']   = $p_fee - $fee;
        return $data;
    }

    /**
     * 获取日常订单费用
     * @param $carType
     * @param $time
     * @param $meter
     * @param $low
     * @param $night
     * @param $isReturn
     * @return mixed
     */
    public static function getDailyFee($carType,$time,$meter,$low,$night,$wait,$isReturn){
        $starting_price  = $carType['starting_price']   ? : 0;
        $Pstarting_price = $carType['p_starting_price'] ? : 0;
        $starting_km     = $carType['starting_km'] ? : 0;
        $starting_time   = $carType['starting_time'] ? : 0;
        $timeCost        = $carType['time_charge'] ? : 0;
        $PTimeCost       = $carType['p_time_charge'] ? : 0;
        $mileage_cost    = $carType['mileage_cost'] ? : 0;
        $Pmileage_cost   = $carType['p_mileage_cost'] ? : 0;
        $transit_cost    = $carType['transit_cost'] ? : 0;
        $Ptransit_cost   = $carType['p_transit_cost'] ? : 0;
        $lowSpeedCost    = $carType['low_speed_cost'] ? : 0;
        $PLowSpeedCost   = $carType['p_low_speed_cost'] ? : 0;
        $nightCost       = $carType['night_driving_cost'] ? : 0;
        $PNightCost      = $carType['p_night_driving_cost'] ? : 0;
        $waitCost        = $carType['waiting_cost'] ? : 0;
        $PWaitCost       = $carType['p_waiting_cost'] ? : 0;
        $waitFee         = $waitCost*$wait;
        $PWaitFee        = $PWaitCost*$wait;
        $mileFee         = $meter/1000 - $starting_km > 0 ? round(($meter/1000-$starting_km)*$mileage_cost,1) : 0;
        $PmileFee        = $meter/1000 - $starting_km > 0 ? round(($meter/1000-$starting_km)*$Pmileage_cost ,1) : 0;
        //返程里程费用8折
        $mileFee         = $isReturn == 1 ? round($mileFee  * config::get('order_return_discount') / 100,1) : $mileFee;
        $PmileFee        = $isReturn == 1 ? round($PmileFee * config::get('order_return_discount') / 100,1) : $PmileFee;
        $timeFee         = $time/60 < $starting_time ? 0 : round(($time/60-$starting_time)*$timeCost,1);
        $PTimeFee        = $time/60 < $starting_time ? 0 : round(($time/60-$starting_time)*$PTimeCost,1);
        $remoteMile      = $meter/1000 - Config::get('base.remote_km');
        $remoteMile      = $remoteMile > 0 ? $remoteMile : 0;
        $remoteFee       = $remoteMile > 0 && $transit_cost >0 ? round($remoteMile*$transit_cost,1) : 0;
        $PRemoteFee      = $remoteMile > 0 && $Ptransit_cost>0 ? round($remoteMile*$Ptransit_cost,1) :0;
        $lowFee          = round($lowSpeedCost*($low/60),1);
        $PLowFee         = round($PLowSpeedCost*($low/60),1);
        $nightFee        = round($nightCost * $night/1000,1);
        $PNightFee       = round($PNightCost * $night/1000,1);
        $fee             = $starting_price + $mileFee + $remoteFee + $lowFee + $nightFee + $timeFee + $waitFee;
        $p_fee           = $Pstarting_price + $PmileFee + $PRemoteFee + $PLowFee + $PNightFee + $PTimeFee + $PWaitFee;
        $data['start_fee']       = $Pstarting_price;
        $data['start_fee2']      = $starting_price;
        $data['wait_fee']        = $PWaitFee;
        $data['wait_fee2']       = $waitFee;
        $data['base_time']       = $starting_time;
        $data['remote_meter']    = $remoteMile*1000;
        $data['remote_fee']      = $PRemoteFee;
        $data['remote_fee2']     = $remoteFee;
        $data['base_meter']      = $starting_km;
        $data['use_time']        = $time;
        $data['time_fee']        = $PTimeFee;
        $data['time_fee2']       = $timeFee;
        $data['low_speed_time']  = $low/60;//单位秒
        $data['low_fee']         = $PLowFee;
        $data['low_fee2']        = $lowFee;
        $data['night_meter']     = $night;
        $data['night_fee']       = $PNightFee;
        $data['night_fee2']      = $nightFee;
        $data['meter']           = $meter;
        $data['travel_fee2']     = $mileFee;
        $data['travel_fee']      = $PmileFee;
        $data['passenger_money'] = $p_fee;
        $data['driver_money']    = $fee;
        $data['company_money']   = $p_fee - $fee;
        return $data;
    }
}
